//
//  SolutionViewController.m
//  ForestPack
//
//  Created by 骆锴 on 2018/7/23.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "SolutionViewController.h"
#import "PackingDesignViewController.h"
#import "SubmitDemandsViewController.h"
#import "EqualCellSpaceFlowLayout.h"
#import "FilterView.h"
#import "SolutionViewCell.h"
#import "SolutionModel.h"
#import <MJRefresh.h>

@interface SolutionViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) NSArray *pictureName;
@property (nonatomic, strong) NSArray *titleName;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSString *cate_id;
@property (nonatomic, strong) NSString *box_id;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;
@property (nonatomic, copy) NSString *pic;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *solutiontitle;

@property (nonatomic, strong) UIButton *shadowBtn;
@property (nonatomic, strong) FilterView *filterView;

@property (nonatomic, strong) NSMutableArray *filterArray;

@property (nonatomic, copy)   NSArray *useArr;
@property (nonatomic, copy)   NSArray *structureArr;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic,assign)  IsOrNotDirecIdType   isOrNotDirecIdType;

@end

@implementation SolutionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _currentPage = 1;
    _dataArray = [[NSMutableArray alloc] init];
    [self initData];
    [self setCollectionView];
    [self setNavBar];
    [self setSubmit];
    [self setFilterView];
}

- (void)initData {
    self.useArr = [NSArray array];
    self.structureArr = [NSArray array];
    
    self.cate_id = @"";
    self.box_id = @"";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setNavBar {
    UIButton *selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(342, 31,20 , 22)];
    [selectBtn setImage:[UIImage imageNamed:@"筛选"] forState:UIControlStateNormal];
    selectBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 5, 0, -5);
    [selectBtn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *selectItem = [[UIBarButtonItem alloc] initWithCustomView:selectBtn];
    self.navigationItem.rightBarButtonItem = selectItem;
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 14, 44)];
    [backBtn setImage:[UIImage imageNamed:@"返回白色"] forState:UIControlStateNormal];
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10);
    [backBtn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    [self setTitle:@"解决方案"];
}

-(void)setCollectionView{
    EqualCellSpaceFlowLayout *flowLayout = [[EqualCellSpaceFlowLayout alloc] initWithType:AlignWithLeft betweenOfCell:ScreenX375(10)];
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(530)) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.scrollEnabled = NO;
    [_collectionView registerClass:[SolutionViewCell class] forCellWithReuseIdentifier:@"solutionCell"];
    [self.view addSubview:_collectionView];
    
    self.collectionView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.collectionView.mj_header beginRefreshing];
}

-(void)setSubmit{
    UIButton *submit = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(530), ScreenX375(349), ScreenX375(44))];
    [submit setTitle:@"提交" forState:UIControlStateNormal];
    [submit addTarget:self action:@selector(turnToSubmit) forControlEvents:1];
    submit.backgroundColor = ThemeColor;
    submit.layer.cornerRadius = 22.0;
    [self.view addSubview:submit];
}

#pragma - UICollectionview

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SolutionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"solutionCell" forIndexPath:indexPath];
    SolutionModel *model = [_dataArray objectAtIndex:indexPath.row];
    cell.layer.cornerRadius = ScreenX375(5);
    [cell.solutionimg sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:nil options:SDWebImageRetryFailed];
    cell.solutionname.text = model.name;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(ScreenX375(170), ScreenX375(130));
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    PackinDesignViewController *vc = [[PackinDesignViewController alloc] init];
    SolutionModel *model = [_dataArray objectAtIndex:indexPath.row];
    vc.product_id = model.solution_id;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma - Methods

- (void)headerRefresh {
    _currentPage = 1;
    self.collectionView.mj_footer.hidden = NO;
    [self getData];
}

- (void)footerRefresh {
    if (_currentPage < _totalPage) {
        _currentPage++;
        [self getData];
        [self.collectionView.mj_footer endRefreshing];
    }else{
        
        [HttpManager showNoteMsg:@"已经到底啦"];
        [self.collectionView.mj_footer endRefreshing];
        self.collectionView.mj_footer.hidden = YES;
    }
}

-(void)getData{
    NSDictionary *parameter = @{@"page":[NSNumber numberWithInteger:_currentPage],@"cate_id":_cate_id,@"box_id":_box_id};
    [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@app/solution_product",REQUESTHEADER] andParameter:parameter success:^(id successResponse){
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSError *error = nil;
            if (self.currentPage == 1) {
                [self.dataArray removeAllObjects];
            }
            self.totalPage = [successResponse[@"data"][@"last_page"] integerValue];
            if (self.totalPage == self.currentPage) {
                self.collectionView.mj_footer.hidden = YES;
            }
            for(NSDictionary *dict in successResponse[@"data"][@"data"]){
                SolutionModel *model = [[SolutionModel alloc] initWithDictionary:dict error:&error];
                model.solution_id = dict[@"id"];
                [self.dataArray addObject:model];
            } if ([successResponse[@"data"][@"data"] count] == 0) {
                [HttpManager showNoteMsg:@"暂无数据"];
                self.collectionView.mj_footer.hidden = YES;
            }
            [self->_collectionView reloadData];
        }
        else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing];
        }else if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing];
        }else if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
    }];
}

-(void)click{
    __weak __typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.shadowBtn.hidden = NO;
        weakSelf.filterView.frame = CGRectMake(SCREEN_WIDTH - ScreenX375(280), 0, ScreenX375(280), SCREEN_HEIGHT);
    }];
}

- (void)hidden {
    __weak __typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.shadowBtn.hidden = YES;
        weakSelf.filterView.frame = CGRectMake(SCREEN_WIDTH, 0, ScreenX375(280), SCREEN_HEIGHT);
    }];
}

-(void)turnTodetial{
    PackinDesignViewController *vc = [[PackinDesignViewController alloc] init];
    self.isOrNotDirecIdType = IsOrNotDirecIdType_Yes;
    vc.isOrNotDirecIdType = self.isOrNotDirecIdType;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)turnToSubmit{
    SubmitDemandsViewController *vc = [[SubmitDemandsViewController alloc] init];
    self.isOrNotDirecIdType = IsOrNotDirecIdType_Yes;
    vc.isOrNotDirecIdType = self.isOrNotDirecIdType;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setFilterView {
    _shadowBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _shadowBtn.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    _shadowBtn.hidden = YES;
    [_shadowBtn addTarget:self action:@selector(hidden) forControlEvents:UIControlEventTouchUpInside];
    [kKeyWindow addSubview:_shadowBtn];
    
    _filterArray = [NSMutableArray arrayWithObjects:@{@"title":@"按结构分类",@"dataArray":[NSMutableArray array]},@{@"title":@"按用途分类",@"dataArray":[NSMutableArray array]}, nil];
    _filterView = [[FilterView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, ScreenX375(280), SCREEN_HEIGHT)];
    __weak __typeof(self) weakSelf = self;
    _filterView.backClick = ^{
        [weakSelf hidden];
    };
    _filterView.doneClick = ^(NSArray *array) {
        [weakSelf hidden];
        if ([array[0] integerValue] < weakSelf.structureArr.count) {
            weakSelf.box_id = [NSString stringWithFormat:@"%@",weakSelf.structureArr[[array[0] integerValue]][@"id"]];
        }else {
            weakSelf.box_id = @"";
        }
        if ([array[1] integerValue] < weakSelf.useArr.count) {
            weakSelf.cate_id = [NSString stringWithFormat:@"%@",weakSelf.useArr[[array[1] integerValue]][@"id"]];
        }else {
            weakSelf.cate_id = @"";
        }
        [weakSelf.collectionView.mj_header beginRefreshing];
    };
    [_filterView modelArrayForView:_filterArray];
    [kKeyWindow addSubview:_filterView];
    
    [self getUse];
    [self getStructure];
}

#pragma NetWork
- (void)getUse{
    [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@app/second_cates",REQUESTHEADER] andParameter:nil success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *dict in successResponse[@"data"]) {
                [array addObject:dict[@"classname"]];
            }
            NSDictionary *dic = @{@"title":@"按用途分类",@"dataArray":array};
            [self.filterArray replaceObjectAtIndex:1 withObject:dic];
            [self.filterView modelArrayForView:self.filterArray];
            self.useArr = successResponse[@"data"];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)getStructure{
    [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@app/structures",REQUESTHEADER] andParameter:nil success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *dict in successResponse[@"data"]) {
                [array addObject:dict[@"cate_name"]];
            }
            NSDictionary *dic = @{@"title":@"按结构分类",@"dataArray":array};
            [self.filterArray replaceObjectAtIndex:0 withObject:dic];
            [self.filterView modelArrayForView:self.filterArray];
            self.structureArr = successResponse[@"data"];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

@end
